<template>
  <div
    id="video-box"
    class="video-box"
    ref="videoBox"
    v-if="reseted"
  >
    <video ref="videoPlayer" class="video-js"></video>
    
    <!-- 进度条 -->
    <div
      class="seek-bar pointer"
      ref="vscVpSeekar"
      v-if="isControlBar"
      @click="onSeekBarClick($event)"
      @mouseenter="showBarPointer"
      @mouseleave="showBarPointer"
      @mousemove="onSeekBarClick($event, 'mouseMove')"
    >
      <!-- 时间tooltip -->
      <div
        class="mouse-time-tip"
        :style="{
          left: `${tipLeft}%`,
          transform: `translateX(-${tipLeft}%)`
        }"
        :class="isBarPointer ? 'visible' : 'hidden'"
      >
        {{ tipText }}
        <div class="mouse-img-tip"></div>
      </div>
      <!-- <progress value="50" max="100"></progress> -->
      <div class="play-bar" :style="{ width: `${sliderTime}%`}">
        <div
          class="bar-point"
          :style="{ left: `${sliderTime}%`}"
          :class="isBarPointer ? 'visible' : 'hidden'"
          @click="onBarPointerClick($event)"
          @mousedown="onBarPointerDgDown($event)"
        ></div>
      </div>
    </div>
    <div v-if="isControlBar" class="control-bar">
      <div class="left-bar">
        <!-- 播放按钮 -->
        <div class="play-btn mright-10 mleft-10" @click="playerVideo">
          <i
            class="iconfont pointer font-30"
            :class="[
              !isPlay ? 'icon-zanting' : 'icon-zanting1',
            ]"
          ></i>
          <!-- <a-icon class="font-26 font-weight" :type="isPlay ? 'caret-right' : 'pause'"/> -->
        </div>
        <!-- 播放下一首 -->
         <a-tooltip placement="top">
          <template slot="title">
            <span>下一个视频</span>
          </template>
          <i
            class="iconfont icon-xiayigexiayishou mright-10 pointer font-24"
            @click="nextVideo"
          ></i>
        </a-tooltip>
        <!-- 视频时长 -->
        <div class="time-wrap">
          <span class="current-time">{{ currentTime }}</span>
          <span class="slash"> / </span>
          <span class="duration">{{ durations }}</span>
        </div>
      </div>
      <div class="right-bar">
        <!-- 视频音量 -->
        <div
          class="volume-btn"
          @mouseenter="isVolume = true"
          @mouseleave="isVolume = false"
        >
          <a-slider
            :sliderStyle="{
              width: '60px',
              'marginTop': '10px'
            }"
            v-show="isVolume"
            :value="volume"
            :tipFormatter="() => volume"
            @changeValue="changeVolume"
          />
          <i
            class="iconfont font-22"
            @click="banNotes"
            :class="[banVolume ? 'icon-jingyin' : 'icon-yinliang']"
          ></i>
        </div>

        <!-- 倍速播放 -->
        <div
          class="play-back-rate pointer"
          @mouseenter="isRateList = true"
          @mouseleave="isRateList = false"
        >
          倍速
          <div class="rate-menu" :class="isRateList ? 'visible' : 'hidden'">
            <ul @click="changeRate">
              <li
                class="rate-item"
                v-for="item in reserveArr(videoOptions.playbackRates)"
                :data-rate='item'
                :class="item === 1.0 ? 'selected' : ''"
                :key="item"
              >{{ `${item}x` }}</li>
            </ul>
          </div>
        </div>
        <!-- 自动播放下一个视频 -->
        <!-- <a-tooltip placement="top">
          <template slot="title">
            <span>自动播放下一个视频</span>
          </template>
          <a-switch
            :checked="isNext"
            size="small"
            @change="isNext = !isNext" />
        </a-tooltip> -->
        <!-- 画中画 -->
        <a-tooltip placement="top">
          <template slot="title">
            <span>{{ pipText }}</span>
          </template>
          <a-icon type="block" class="font-22" @click="openPIP" />
        </a-tooltip>
        <!-- 全屏 -->
        <div class="full-screen-btn">
          <a-tooltip placement="top">
            <template slot="title">
              <span>全屏</span>
            </template>
            <i
              class="iconfont font-22 pointer"
              @click="fullScreen"
              :class="!isFullScreen ? 'icon-FullScreen' : 'icon-a-122-tuichuquanping'"
            ></i>
          </a-tooltip>
        </div>
      </div>
    </div>
    <!-- 全屏播放按钮 -->
    <div v-if="isControlBar" class="full-btn" @click="playerVideo($event)">
      <i
        v-show="isPlay"
        class="iconfont icon-zanting1 pointer"
      ></i>
    </div>
    <!-- 正在加载 -->
    <!-- <div class="loading-wait" :class="loading ? 'visible' : 'hidden'">
      正在加载...
    </div> -->
    <!-- 视频加载错误 -->
    <div class="error-msg pointer font-20" @click="reloadUrl" v-if="showError">
      加载出错,点击刷新
      <a-icon type="redo" class="selected" />
    </div>
  </div>
</template>

<script>
import Videojs from 'video.js';
import "video.js/dist/video-js.min.css";
import Slider from '../Library/Slider';
import { Tooltip } from 'ant-design-vue';
import { formatTime } from '@/utils/figure';
export default {
  name: 'videoPlayer',

  components: {
    ASlider: Slider,
    ATooltip: Tooltip,
    // ASwitch: Switch
  },

  props: {
    options: {
      type: Object,
      require: true
    },
    // 相关视频推荐
    // otherList: {
    //   type: Array,
    //   default: () => {}
    // },
    playsinline: {
      type: Boolean,
      default: false
    }
  },

  data() {
    return {
      reseted: true,
      player: null,
      // 暂停或播放按钮控制
      isPlay: true,
      // 控制操作栏显示隐藏
      isControlBar: true,
      // 控制滑块圆点显示隐藏
      isBarPointer: false,
      // 是否自动播放下一个视频
      // isNext: false,
      // 是否禁音
      banVolume: false,
      // 音量大小 默认最大声
      volume: 100,
      isVolume: false,
      // 是否显示倍速列表
      isRateList: false,
      draging: false,
      // 进度条宽度
      sliderTime: 0,
      // 当前视频时长
      currentTime: '00:00',
      // 视频总时长
      durations: '00:00',
      // 画中画文本
      pipText: '开启画中画',
      // 全屏模式
      isFullScreen: false,
      // 加载出错时
      showError: false,
      // tip文本
      tipText: '00:00',
      // tip偏移量
      tipLeft: 0,
      loading: true,
      videoOptions: {
        autoplay: false, //自动播放
        //用户可以与之交互的控件
        controls: false,
        // 默认播放倍速列表
        playbackRates: [0.5, 0.75, 1.0, 1.25, 1.5, 2.0],
        //视频容器高度
        // height: 360,
        //视频一结束就重新开始
        loop: false,
        //默认情况下将使所有音频静音
        muted: false,
        // 播放前显示的视频画面,播放开始后自动移除
        // poster: 'https://p2.music.126.net/Fh-1DbO1zNvGLTf83BEgNA==/109951163573866074.jpg?param=320y180',
        aspectRatio: "16:9", //显示比率
        // 预加载,metadata元数据信息、none不预加载任何数据
        preload: 'auto',
        // 使播放器具有流畅大小
        fluid: true,
        // fullscreen:{
        //   options: {
        //     navigationUI: 'hide'
        //   }
        // },
        // sources: [
        //   {
        //     src: "http://vjs.zencdn.net/v/oceans.mp4",
        //     type: "video/mp4"
        //   }
        // ]
      }
    }
  },

  computed: {
    vplayer() {
      return this.$refs.videoPlayer;
    },
    vBox() {
      return this.$refs.videoBox;
    },
    // controlBars: {
    //   get() {
    //     return this.controlBar;
    //   },
    //   set(value) {
    //     this.controlBar = value;
    //   }
    // }
  },

  watch: {
    options: {
      handler(options, old) {
        console.log(options, old)
        if (!this.vplayer) {
          // 自定义的错误样式
          this.showError = true;
          // 如果已经报错,控制栏也不应该显示了
          this.isControlBar = false;
          return;
        }
        if (options && options.sources && options.sources.length) {
          // if (options[0].src !== oldOptions[0].src) {
          //   this.vplayer.src(options[0].src);
          // }
          this.initVideojs();
        }
      },
      deep: true,
      // immediate: true
    }
  },

  methods: {
    initVideojs() {

      if (this.playsinline) {
        this.vplayer.setAttribute('playsinline', this.playsinline);
        this.vplayer.setAttribute('webkit-playsinline', this.playsinline);
        this.vplayer.setAttribute('x5-playsinline', this.playsinline);
        this.vplayer.setAttribute('x5-video-player-type', 'h5');
        this.vplayer.setAttribute('x5-video-player-fullscreen', false);
      }

      const videoOptions = Object.assign({}, this.videoOptions, this.options);
      console.log(videoOptions)
      Videojs.hook('beforeerror', (player, err) => {
        console.log('hook - beforeerror', player.src(), err)
        // Video.js 在切换/指定 source 后立即会触发一个 err=null 的错误，这里过滤一下
        if (err !== null) {
          // player.src(sources[++index])
          // 隐藏controlbar
          this.isControlBar = false;
          // 隐藏视频中间的播放按钮
          this.showError = true;
        }

        // 清除错误，避免 error 事件在控制台抛出错误
        return null
      });
      
      const _this = this;
      this.player = Videojs(this.vplayer, videoOptions, function() {
        this.on("loadstart", function() {
          console.log("开始请求数据");
          // if (!this.isPlay) {
            this.isPlay = true;
          // }
          // 重置进度条
          // if (this.sliderTime) {
            this.sliderTime = 0;
          // }
        })
        this.on("progress", function(e) {
          console.log("正在请求数据", e);
        })
        this.on("loadedmetadata", function(e) {
          console.log("获取资源长度完成", e);
        })
        this.on("canplaythrough", function() {
          console.log("视频源数据加载完成");
          const timeObj = formatTime(_this.vplayer.duration);
          _this.durations = `${timeObj.min}:${timeObj.max}`;
          // 默认当前视频时间是00:00
          _this.currentTime = '00:00';
        })
        this.on("waiting", function() {
          console.log("等待数据")
        });
        this.on("play", function() {
          console.log("视频开始播放");
          _this.isPlay = false;
          // 初始化视频声音最大
          _this.vplayer.volume = 1;
        });
        // this.on("playing", function() {
        //   console.log("视频播放中");
        // });
        this.on("pause", function() {
          console.log("视频暂停播放");
          _this.isPlay = true;
        });
        this.on("ended", function() {
          console.log("视频播放结束");
          _this.isPlay = true;
          // if (_this.isNext) {
          //   // 不再循环播放
          //   // this.vplayer.loop = false;
          //   this.$emit('loopNextVideo');
          // }
        });
        this.on("error", function() {
          console.log("加载错误");
          _this.vplayer.errorDisplay.close();
          this.showError = true;
          this.isControlBar = false;
        });
        // this.on("seeking",function() {
        //   console.log("视频跳转中");
        // })
        // this.on("seeked",function() {
        //   console.log("视频跳转结束");
        // })
        // this.on("ratechange", function() {
        //   console.log("播放速率改变")
        // });
        this.on("timeupdate", function() {
          console.log("播放时长改变");
          let currentTime = _this.vplayer.currentTime;
          _this.sliderTime =
            parseInt((currentTime / _this.vplayer.duration) * 100);
          // 获取当前时间并转换成00:00
          const timeObj = formatTime(currentTime);
          _this.currentTime = `${timeObj.min}:${timeObj.max}`;
        });
        this.on("enterpictureinpicture", function(e) {
          console.log(e, '画中画开启', document.pictureInPictureElement);
          _this.pipText = '关闭画中画';
        });
        // 监听退出画中画
        this.on("leavepictureinpicture", function() {
          _this.pipText = '开启画中画';
        });
        // this.on("fullscreenchange", function() {
        //   if (!_this.checkIsFullScreen()) {
        //     _this.isFullScreen = false;
        //   }
        // });
        this.on("volumechange", function() {
          console.log("音量改变");
        })
        this.on("stalled", function() {
          console.log("网速异常");
          sessionStorage.setItem('currentTime', _this.vplayer.currentTime);
          _this.$message.error('┗|｀O′|┛ 嗷~~,请检查网络');
        })
      });

    },
    // 移入移除显示操作栏
    // showControlBar() {
    //   this.isControlBar = !this.isControlBar;
    // },
    // 移入移出显示滑块圆点
    showBarPointer() {
      this.isBarPointer = !this.isBarPointer;
    },
    // 滑块圆点拖动事件
    onBarPointerDgDown(e) {
      // 禁止默认事件
      e.preventDefault();
      this.draging = true;
      window.addEventListener("mouseup", this.onDragEnd);
      window.addEventListener("mousemove", this.onDragging);
    },
    // 结束拖动
    onDragEnd() {
      if (this.draging == true) {
        this.draging = false;
      }
      window.removeEventListener("mouseup", this.onDragEnd);
      window.removeEventListener("mousemove", this.onDragging);
    },
    onDragging(e) {
      if (this.draging) {
        let left = this.$refs.vscVpSeekar.getBoundingClientRect().left;
        if (e.clientX - left < this.$refs.vscVpSeekar["clientWidth"]) {
          this.onSeekBarClick(e);
        }
      }
    },
    onSeekBarClick(e, type) {
      let left = this.$refs.vscVpSeekar.getBoundingClientRect().left;
      // 获取光标位置
      const width = parseInt(
        ((e.clientX - left) / this.$refs.vscVpSeekar["clientWidth"]) * 100
      );
      const cTime = (width / 100) * this.vplayer.duration;
      if (type === 'mouseMove') {
        this.tipLeft = width ;
        this.tipText = `${formatTime(cTime).min}:${formatTime(cTime).max}`;
      } else {
        this.sliderTime = width;
        // 拖动滑块改变video播放时间
        this.vplayer.currentTime = cTime;
      }
    },
    onBarPointerClick(e) {
      // 兼容ie
      e.stopPropagation ? e.stopPropagation() : (e.cancelBubble = true);
    },
    // 点击重新加载
    reloadUrl() {
      // 说明sources都没有,没有初始化video
      if (!this.vplayer) {
        this.$emit('reloadinterface', true);
      } else {
        if (this.options && this.options.sources && this.options.sources[0].url) {
          this.vplayer.load();
          this.showError = false;
          this.isControlBar = true;
        } else {
          this.$emit('reloadinterface', true);
        }
      }
    },
    // 点击播放
    playerVideo(e) {
      e.stopPropagation();
      this.isPlay ? this.vplayer.play() : this.vplayer.pause();
    },
    // 是否静音
    banNotes() {
      this.banVolume = !this.banVolume;
      this.banVolume ?
        this.vplayer.muted = true : this.vplayer.muted = false;
    },
    // 改变音量大小
    changeVolume(value) {
      this.volume = value;
      // audio中的volume取值只能0-1这个范围
      this.vplayer.volume = value / 100;
      if (!value) {
        this.banVolume = true;
        return;
      }
      this.banVolume = false;
    },
    // 改变倍速
    changeRate(event) {
      event.stopPropagation();
      const { rate } = event.target.dataset;
      const prev = document.querySelector('.selected');
      // if (event.target.classLis)
      this.vplayer.playbackRate = rate;
      // 如果两次选中的是同一速率,不再执行后续代码
      if (prev.innerHTML === event.innerHTML) return;
      // 去掉上一个selected
      prev.classList.remove('selected');
      event.target.classList.add('selected');
      this.isRateList = false;
    },
    // 开启画中画
    openPIP() {
      // 判断是否支持画中画模式
      if ('pictureInPictureEnabled' in document === false) {
        this.$message.open({
          icon: this.$createElement('a-icon', {
            props: {
              type: 'frown'
            }
          }),
          content: '┗|｀O′|┛ 嗷~~,浏览器不支持开启画中画'
        })
      } else {
        // 判断画中画是否开启
        if (!document.pictureInPictureElement) {
          // this.pipText = '关闭画中画';
          this.vplayer.requestPictureInPicture();
        } else { //关闭画中画
          // this.pipText = '开启画中画';
          document.exitPictureInPicture();
        }
      }
    },
    // 点击全屏按钮
    fullScreen() {
      this.isFullScreen ? this.exitFullScreen() : this.requestFullScreen()
      this.isFullScreen = !this.isFullScreen;
    },
    requestFullScreen() {
      let request = 
        this.vBox.requestFullscreen ||
        this.vBox.webkitRequestFullScreen  ||
        this.vBox.mozRequestFullScreen ||
        this.vBox.msRequestFullScreen;
      if (!request) {
        this.$message.open({
          icon: this.$createElement('a-icon', {
            props: {
              type: 'frown'
            }
          }),
          content: '┗|｀O′|┛ 嗷~~,浏览器不支持全屏播放'
        });
        return;
      }
      // this.fullText = '退出全屏';
      request.call(this.vBox);
    },
    exitFullScreen() {
      let exit = 
        document.exitFullscreen ||
        document.mozCancelFullScreen  ||
        document.webkitExitFullscreen ||
        document.msExitFullscreen
      if (!exit) {
        this.$message.open({
          icon: this.$createElement('a-icon', {
            props: {
              type: 'frown'
            }
          }),
          content: '┗|｀O′|┛ 嗷~~,已经不是全屏状态了'
        });
        return;
      }
      // this.fullText = '全屏';
      exit.call(document);
    },
    // 播放下一个视频
    nextVideo() {
      this.$emit('next');
    },
    // 反转数组
    reserveArr(arr) {
      const newArr = [];
      arr.forEach(item => {
        newArr.unshift(item);
      });
      return newArr;
    },

    // video销毁二次封装
    dispose() {
      if (this.vplayer && this.vplayer.dispose) {
        if (this.vplayer.techName_ !== 'Flash') {
          this.vplayer.pause && this.vplayer.pause()
        }
        this.vplayer.dispose();
        this.vplayer = null;
        this.$nextTick(() => {
          this.reseted = false
          this.$nextTick(() => {
            this.reseted = true
            // this.$nextTick(() => {
            //   callback && callback()
            // })
          })
        })
      }
    }
  },

  mounted() {
    // if (!this.vplayer) {
    //   this.initVideojs();
    // }
    // 监听是否退出全屏
    // const isFull =
    //   document.fullscreenEnabled || window.fullScreen || document.webkitIsFullScreen || document.msFullscreenEnabled;
    // window.addEventListener('resize', () => {
    //   console.log(isFull);
    //   if (isFull === undefined) {
    //     this.fullText = '全屏';
    //     this.isFullScreen = false;
    //   } else {
    //     this.fullText = '退出全屏';
    //     this.isFullScreen = true;
    //   }
    // });
  },

  beforeDestroy() {
    if (this.player) {
      this.dispose();
    }
  }
}
</script>

<style lang="less" scoped>
#video-box {
  position: relative;
  // min-height:;
  // 去掉全屏时显示的controlbar
  video::-webkit-media-controls {
    display: none !important;
  }
  .video-js {
    width: 100%;
    height: 100%;
  }
  // .video-js .vjs-error .vjs-error-display::before {
  //   display: none !important;
  // }
  // #video-bw {
  //   position: absolute;
  //   left: 50%;
  //   transform: translateX(-50%);
  //   height: 100%;
  // }
  .seek-bar{
    position: absolute;
    bottom: 2.8rem;
    width: calc(100% - 10px);
    height: 5px;
    background: #fff;
    margin: 0 5px;
    // border-radius: 5px;
    z-index: 99;
    .play-bar {
      // width: 20%;
      height: 100%;
      background: red;
      cursor: pointer;
      transition: width .5s;
      .bar-point {
        position: absolute;
        top: -5px;
        // left: 20%;
        display: inline-block;
        width: 15px;
        height: 15px;
        border-radius: 50%;
        background: #fff;
        cursor: pointer;
        transition: left .5s;
      }
    }
    .mouse-time-tip {
      display: flex;
      justify-content: center;
      position: absolute;
      top: -25px;
      background: rgba(0, 0, 0, .6);
      color: #fff;
      padding: 0 10px;
      .mouse-img-tip {
        position: absolute;
        width: 160px;
        height: 90px;
        background-image: url(//lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M/byted-player-videos/1.0.0/xgplayer-demo-thumbnail.jpg);
        background-position: -1440px -90px;
        top: -90px;
      }
    }
  }
  .control-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: absolute;
    bottom: 0;
    height: 2.8rem;
    // line-height: 2.8rem;
    width: 100%;
    color: #fff;
    background-image: linear-gradient(180deg,transparent,rgba(0,0,0,.37),rgba(0,0,0,.75),rgba(0,0,0,.75));
    // z-index: 999;
    .left-bar,
    .right-bar {
      display: flex;
      align-items: center;
      /deep/button.ant-switch.ant-switch-small {
        margin-right: 10px;
      }
    }
    .time-wrap {
      line-height: 22px;
      height: 22px;
      font-size: 12px;
      position: relative;
      margin: 0 10px 0 0;
      cursor: pointer;
      min-width: 90px;
      .slash {
        margin: 0 6px;
      }
    }
    .volume-btn {
      display: flex;
      align-items: center;
      flex-direction: row-reverse;
      margin-right: 10px;
    }
    .play-back-rate {
      width: 60px;
      position: relative;
      text-align: center;
      .rate-menu {
        min-width: 80px;
        position: absolute;
        bottom: 20px;
        transform: translateX(-50%);
        left: 50%;
        background: rgba(0, 0, 0, 0.6);
        z-index: 999;
        border-radius: 3px;
        >ul {
          margin-bottom: 0 !important;
          .rate-item {
            padding: 6px 0;
            &:hover {
              color: hsla(0, 0%, 100%, .8);
            }
          }
        }
      }
    }
    .full-screen-btn {
      width: 60px;
      text-align: center;
    }
  }
  .error-msg,
  .full-btn {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    width: 100%;
    height: 100%;
    background-color: #000;
    color: #fff;
    z-index: 99;
  }
  .full-btn {
    height: calc(100% - 3.3rem);
    background-color: transparent;
    z-index: 0;
    >i {
      font-size: 70px;
    }
  }
  .loading-wait {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: #fff;
    font-size: 20px;
  }
  .visible {
    visibility: visible;
  }
  .hidden {
    visibility: hidden;
  }
  .selected {
    color: #ec4141;
    font-weight: 700;
  }
}
</style>